package com.lytoyo.neihanduanzi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lytoyo.neihanduanzi.mapper.BlogCommentMapper;
import com.lytoyo.neihanduanzi.mapper.BlogMapper;
import com.lytoyo.neihanduanzi.model.Result;
import com.lytoyo.neihanduanzi.model.blog.BlogComment;
import com.lytoyo.neihanduanzi.model.blog.BlogInfo;
import com.lytoyo.neihanduanzi.model.dto.BlogCommentDto;
import com.lytoyo.neihanduanzi.model.dto.BlogCommentVo;
import com.lytoyo.neihanduanzi.model.user.UserInfo;
import com.lytoyo.neihanduanzi.service.BlogCommentService;
import com.lytoyo.neihanduanzi.service.BlogService;
import com.lytoyo.neihanduanzi.service.UserService;
import com.lytoyo.neihanduanzi.utils.AuthContextHolder;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Package:com.lytoyo.neihanduanzi.service.impl
 *
 * @ClassName:BlogCommentServiceImpl
 * @Create:2025/3/16 10:48
 **/
@Service
@Slf4j
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentMapper, BlogComment> implements BlogCommentService {
    @Resource
    private BlogCommentMapper blogCommentMapper;

    @Resource
    private BlogMapper blogMapper;

    @Resource
    private BlogService blogService;

    @Resource
    private UserService userService;

    /**
     * 分页查询博客评论
     *
     * @param page
     * @param blogId
     * @return
     */
    @Override
    public Map gainComment(Page<BlogComment> page, Long blogId) {
        //查询父级评论
        Page<BlogComment> commentPage = blogCommentMapper.selectPage(page, new LambdaQueryWrapper<BlogComment>()
                .eq(BlogComment::getBlogId, blogId)
                .eq(BlogComment::getRootComment, 0));
        List<BlogComment> records = commentPage.getRecords();
        List<HashMap<String, Object>> list = new ArrayList<>();
        for (BlogComment blogComment : records) {
            HashMap<String, Object> commentMap = new HashMap<>();
            Long id = blogComment.getId();

            //查询每条父评论下有几条子评论
            Long count = blogCommentMapper.selectCount(new LambdaQueryWrapper<BlogComment>()
                    .eq(BlogComment::getRootComment, 1)
                    .eq(BlogComment::getToRootCommentId, id));
            if (count > 0) {
                commentMap.put("childCommentCount", count);
            } else {
                commentMap.put("childCommentCount", 0);
            }
            //根据父级评论查看其userId所对应的头像，昵称等信息
            UserInfo userInfo = userService.getById(blogComment.getUserId());
            BlogCommentVo blogCommentVo = new BlogCommentVo().setNickname(userInfo.getNickname()).setHeadPhoto(userInfo.getHeadPhoto());
            BeanUtils.copyProperties(blogComment,blogCommentVo, BlogCommentVo.class);
            //将父评论添加到rootCommentMap中
            commentMap.put("rootComment", blogCommentVo);
            list.add(commentMap);
        }
        HashMap<String, Object> map = new HashMap<>();

        map.put("comment", list);
        //当前页
        map.put("current", page.getCurrent());
        //总记录数
        map.put("total", page.getTotal());
        //总页数
        map.put("pages", page.getPages());
        //是否有下一页
        map.put("hasNext", page.hasNext());
        return map;
    }

    /**
     * 添加评论
     *
     * @param blogCommentDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result addComment(BlogCommentDto blogCommentDto) {
        Long userId = AuthContextHolder.getUserId();
        //判断当前博客是否还存在
        BlogInfo blogInfo = blogMapper.selectOne(new LambdaQueryWrapper<BlogInfo>().eq(BlogInfo::getId, blogCommentDto.getBlogId()));
        if (null == blogInfo) {
            return Result.fail(-1, "当前视频已下架");
        }
        UserInfo userInfo = userService.getById(userId);
        //判断当前是否为父评论
        if (null != blogCommentDto.getRootComment() && blogCommentDto.getRootComment() == 0) {
            BlogComment blogComment = new BlogComment();
            //存入数据库并响应
            BeanUtils.copyProperties(blogCommentDto, blogComment, BlogComment.class);
            blogComment.setUserId(userId)
                       .setHeadPhoto(userInfo.getHeadPhoto())
                       .setNickname(userInfo.getNickname())
                       .setLikedCount(0L)
                       .setToRootCommentId(0L)
                       .setRootComment(0);
            this.save(blogComment);
            //评论数量+1
            this.blogService.update(new LambdaUpdateWrapper<BlogInfo>().eq(BlogInfo::getId,blogComment.getBlogId()).setSql("comment = comment + 1"));
            return Result.success(blogComment);
        }
        //如果为子评论，判断对应的父评论是否还存在
        if (null != blogCommentDto.getToRootCommentId() && 0 != blogCommentDto.getToRootCommentId()) {
            BlogComment rootComment = this.getOne(new LambdaQueryWrapper<BlogComment>()
                    .eq(BlogComment::getId, blogCommentDto.getToRootCommentId()));
            //将该评论存入数据库
            if (null != rootComment) {
                BlogComment blogComment = new BlogComment();
                BeanUtils.copyProperties(blogCommentDto, blogComment, BlogComment.class);
                blogComment.setUserId(userId)
                        .setNickname(userInfo.getNickname())
                        .setHeadPhoto(userInfo.getHeadPhoto())
                        .setLikedCount(0L)
                        .setRootComment(1)
                        .setToRootCommentId(blogCommentDto.getToRootCommentId());
                this.save(blogComment);
                //评论数量+1
                this.blogService.update(new LambdaUpdateWrapper<BlogInfo>().eq(BlogInfo::getId,blogComment.getBlogId()).setSql("comment = comment + 1"));
                return Result.success(blogComment);
            } else {
                return Result.fail(-1, "当前评论已不存在");
            }
        } else {
            return Result.fail(-1, "数据异常");
        }
    }

    /**
     * 获取子评论
     * @param page
     * @param rootCommentId
     * @return
     */
    @Override
    public Map gainChildComment(Page<BlogComment> page,Long rootCommentId) {
        //分页查询子评论
        Page<BlogComment> commentPage = this.blogCommentMapper.selectPage(page, new LambdaQueryWrapper<BlogComment>()
                .eq(BlogComment::getToRootCommentId, rootCommentId)
                .eq(BlogComment::getRootComment, 1));
        List<BlogComment> records = commentPage.getRecords();
        List<HashMap<String,Object>> list = new ArrayList<>();
        //查询每条子评论的用户头像，昵称等信息
        for (BlogComment blogComment:records){
            HashMap<String, Object> commentMap = new HashMap<>();
            UserInfo userInfo = this.userService.getById(blogComment.getUserId());
            BlogCommentVo blogCommentVo = new BlogCommentVo().setNickname(userInfo.getNickname()).setHeadPhoto(userInfo.getHeadPhoto());
            BeanUtils.copyProperties(blogComment,blogCommentVo, BlogCommentVo.class);
            commentMap.put("childComment",blogCommentVo);
            list.add(commentMap);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("comment",list);
        map.put("hasNext",page.hasNext());
        return map;
    }

    /**
     * 评论
     * @param blogCommentDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result comment(BlogCommentDto blogCommentDto) {
        Long userId = AuthContextHolder.getUserId();
        BlogComment blogComment = new BlogComment().setLikedCount(0l).setUserId(userId);
        BeanUtils.copyProperties(blogCommentDto,blogComment,BlogComment.class);
        //前端对是否是父级评论，子评论等限制已经做好，只需存入数据库
        this.save(blogComment);
        //博客评论数量+1
        this.blogService.update(new LambdaUpdateWrapper<BlogInfo>().eq(BlogInfo::getId,blogComment.getBlogId()).setSql("comment = comment + 1"));
        return Result.success("评论成功");
    }


}
























